/** @format */
const { Controller } = require("egg");

class TeamController extends Controller {
    async index() {
        const { ctx } = this;
        ctx.body = "hi, egg";
    }
    gettoken() {
        const { ctx, app } = this;
        let clientdata = ctx.request.body;
        let userinfo = null;
        try {
            userinfo = app.jwt.verify(ctx.request.header.token, app.config.jwt.secret);
            console.log(userinfo, "我是用户");

            // console.log(post, 'post')
        } catch (error) {
            console.error(error);
            userinfo = false;
            // Expected output: ReferenceError: nonExistentFunction is not defined
            // (Note: the exact output may be browser-dependent)
        }
        return userinfo;
    }
    async addteam() {
        const { ctx, app } = this;
        let clientdata = ctx.request.body;
        console.log(clientdata, "clientdata");
        // 生成团队id 9位数字的随机数，一次生成9位数
        let getroudnm = async () => {
            let Array = [];
            for (let i = 0; i < 9; i++) {
                Array.push(Math.round(Math.random() * 9));
            }
            let post = await this.app.mysql.get("volunteer_team", {
                team_id: Array.join(""),
            });

            if (post) {
                console.log("存在");
                getroudnm();
            } else {
                console.log("不存在");
                return Array.join("");
            }
        };
        let team_id = await getroudnm();
        console.log(team_id, "getroudnm");
        // 插入数据库
        const result = await this.app.mysql.insert(
            "volunteer_team",

            {
                name: clientdata.name,
                captain_id: clientdata.captain_id,
                manifesto: clientdata.manifesto,
                introduction: clientdata.introduction,
                team_flag: clientdata.team_flag[0],
                captain_name: clientdata.captain_name,
                team_id: team_id,
            },
        ); // 在 posts 表中，插入 title 为 Hello World 的记录
        clientdata.groups.forEach((item) => {
            this.app.mysql.insert("team_groups", {
                name: item,
                team_id: team_id,
            });
        });
        // 插入队长信息
        const result2 = await this.app.mysql.insert("team_members", {
            team_id: team_id,
            member_id: clientdata.captain_id,
            hobbies: clientdata.hobbies,
            ismanage: "true",
            biography: clientdata.biography,
            photo: clientdata.photo[0],
            posts: "队长",
            state: 1,
        });

        if (result) {
            ctx.body = {
                code: 200,
                desp: "添加成功",
                data: result,
            };
        } else {
            ctx.body = {
                code: 201,
                desp: "添加失败",
            };
        }
    }
    async getteamlist() {
        const { ctx, app } = this;
        let clientdata = ctx.request.body;
        console.log(ctx.request.header.token, "ssssssssssss");
        let userinfo = this.gettoken();
        // let Query = "name like %星河%";
        let teamlist = clientdata.Query ? await app.mysql.query(`SELECT * FROM volunteer_team  WHERE ${clientdata.Query}`) : await app.mysql.query(`SELECT * FROM volunteer_team  `);
        // let res = await app.mysql.query(`SELECT * FROM article WHERE atitle LIKE '%${clientdate.txt}%' or alabel like '%${clientdate.txt}%'  or alabel like '%${clientdate.txt}%' `);
        console.log(teamlist, "teamlist");

        // let data = {
        //     where: {
        //         // ...(clientdata.Query ? clientdata.Query : {}),
        //         name: {
        //             [Op.like]: "%星河%",
        //         },
        //     },
        //     limit: clientdata.pagesize,
        //     offset: (clientdata.pageindex - 1) * clientdata.pagesize,
        //     order: [["id"]],
        // };

        // console.log(data, "data");
        // let teamlist = await this.app.mysql.select("volunteer_team", data);
        await Promise.all(
            teamlist.map(async (item, index) => {
                let groups = await this.app.mysql.select("team_groups", {
                    where: { team_id: item.team_id },
                });
                teamlist[index].groups = groups;
                if (userinfo) {
                    let ismember = await this.app.mysql.get("team_members", {
                        member_id: userinfo.userid,
                        team_id: item.team_id,
                    });
                    teamlist[index].ismember = ismember;
                }
            }),
        );

        ctx.body = {
            code: 200,
            desp: "查询成功",
            data: teamlist,
        };
    }
    async getallteamlist() {
        const { ctx, app } = this;
        let clientdata = ctx.request.body;
        console.log(ctx.request.header.token, "ssssssssssss");
        let userinfo = this.gettoken();
        let data = {
            where: {
                ...(clientdata.Query ? clientdata.Query : {}),
            },
            limit: clientdata.pagesize,
            offset: (clientdata.pageindex - 1) * clientdata.pagesize,
            order: [["id"]],
        };

        console.log(data, "data");
        let teamlist = await this.app.mysql.select("volunteer_team", data);
        await Promise.all(
            teamlist.map(async (item, index) => {
                let groups = await this.app.mysql.select("team_groups", {
                    where: { team_id: item.team_id },
                });
                teamlist[index].groups = groups;
                if (userinfo) {
                    let ismember = await this.app.mysql.get("team_members", {
                        member_id: userinfo.userid,
                        team_id: item.team_id,
                    });
                    teamlist[index].ismember = ismember;
                }
            }),
        );

        ctx.body = {
            code: 200,
            desp: "查询成功",
            data: teamlist,
        };
    }
    async getmyaddteamlist() {
        const { ctx, app } = this;
        let clientdata = ctx.request.body;
        console.log(ctx.request.header.token, "ssssssssssss");
        let userinfo = {};
        let myarrayteam = [];
        try {
            userinfo = app.jwt.verify(ctx.request.header.token, app.config.jwt.secret);
            console.log(userinfo, "我是用户");
            let data2 = {
                // 搜索 posts 表
                where: { member_id: userinfo.userid }, // WHERE 条件
            };
            let team_members = await this.app.mysql.select("team_members", data2);
            console.log(team_members, "team_membersteam_members");
            myarrayteam = team_members.map((item) => {
                return item.team_id;
            });
            console.log(myarrayteam, "myarrayteam");
            // console.log(post, 'post')
        } catch (error) {
            console.error(error);
            userinfo = false;
            // Expected output: ReferenceError: nonExistentFunction is not defined
            // (Note: the exact output may be browser-dependent)
        }
        console.log(myarrayteam, "myarrayteam");

        let data = {
            where: {
                ...(clientdata.Query ? clientdata.Query : {}),
                team_id: myarrayteam,
            },
            limit: clientdata.pagesize,
            offset: (clientdata.pageindex - 1) * clientdata.pagesize,
            order: [["id"]],
        };

        console.log(data, "data");
        let teamlist = await this.app.mysql.select("volunteer_team", data);
        await Promise.all(
            teamlist.map(async (item, index) => {
                let groups = await this.app.mysql.select("team_groups", {
                    where: { team_id: item.team_id },
                });
                teamlist[index].groups = groups;
                if (userinfo) {
                    let ismember = await this.app.mysql.get("team_members", {
                        member_id: userinfo.userid,
                        team_id: item.team_id,
                    });
                    teamlist[index].ismember = ismember;
                }
            }),
        );

        ctx.body = {
            code: 200,
            desp: "查询成功",
            data: teamlist,
        };
    }
    async modifyteam() {
        const { ctx } = this;
        let clientdata = ctx.request.body;
        console.log(clientdata, "clientdata");
        // 插入数据库
        const result = await this.app.mysql.update(
            "volunteer_team",
            {
                name: clientdata.name,
                manifesto: clientdata.manifesto,
                introduction: clientdata.introduction,
                team_flag: clientdata.team_flag[0],
            },
            { where: { team_id: clientdata.team_id } },
        );
        console.log(clientdata.team_id, "clientdata.team_id");
        const result2 = await this.app.mysql.delete("team_groups", {
            team_id: clientdata.team_id,
        });
        console.log(result2);
        clientdata.groups.forEach((item) => {
            this.app.mysql.insert("team_groups", {
                name: item,
                team_id: clientdata.team_id,
            });
        });
        if (result) {
            ctx.body = {
                code: 200,
                desp: "修改成功",
                data: result,
            };
        } else {
            ctx.body = {
                code: 201,
                desp: "修改失败",
            };
        }
    }
    async deleteteam() {
        const { ctx } = this;
        let clientdata = ctx.request.body;
        console.log(clientdata, "clientdata");
        // 删除队伍
        const result = await this.app.mysql.delete("volunteer_team", {
            team_id: clientdata.team_id,
        });
        // 删除分组
        const result2 = await this.app.mysql.delete("team_groups", {
            team_id: clientdata.team_id,
        });
        // 删除成员
        const result3 = await this.app.mysql.delete("team_members", {
            team_id: clientdata.team_id,
        });
        // result2.forEach(element => {
        //        this.app.mysql.delete("team_groups", {
        //             team_id: clientdata.team_id,
        // });

        // });
        if (result && result2) {
            ctx.body = {
                code: 200,
                desp: "删除成功",
                data: result,
            };
        } else {
            ctx.body = {
                code: 201,
                desp: "删除失败",
            };
        }
    }
    // 人员结构
    async getteamgroups() {
        const { ctx } = this;
        let clientdata = ctx.request.body;
        console.log(clientdata, "clientdata");
        let team = await this.app.mysql.select("volunteer_team", {
            where: { team_id: clientdata.team_id },
        });
        let teamobj = {
            name: team[0].name,
            id: team[0].team_id,
            children: [],
        };
        let groups = await this.app.mysql.select("team_groups", {
            where: { team_id: clientdata.team_id },
        });
        await Promise.all(
            groups.map(async (item) => {
                let members = await this.app.mysql.select("team_members", {
                    where: { group_id: item.id },
                });
                let newmembers = [];
                await Promise.all(
                    (members = members.map(async (item) => {
                        item.photo = [item.photo];
                        let memberuserinfo = await this.app.mysql.select("userinfo", {
                            where: { id: item.member_id },
                        });
                        console.log(memberuserinfo, "memberuserinfo");
                        console.log(item.id, "sssssssssssssss");
                        newmembers.push({
                            id: item.id,
                            name: memberuserinfo[0].realname,
                        });
                        console.log(newmembers, "newnewnew");
                    })),
                );
                teamobj.children.push({
                    name: item.name,
                    id: item.id,
                    children: newmembers,
                });
            }),
        );
        console.log(teamobj, "teamobjteamobjteamobjteamobj");
        ctx.body = {
            code: 200,
            desp: "查询成功",
            data: teamobj,
        };
    }
    // 人员列表
    async getteammembers() {
        const { ctx, app } = this;
        let clientdata = ctx.request.body;
        let data = {
            // 搜索 posts 表
            where: { ...(clientdata.Query ? clientdata.Query : "") }, // WHERE 条件
            limit: clientdata.pagesize, // 返回数据量
            offset: (clientdata.pageindex - 1) * clientdata.pagesize, // 数据偏移量
            orders: [["id"]], // 排序方式
        };
        console.log(data, "data");
        let memberslist = await this.app.mysql.select("team_members", data);
        await Promise.all(
            memberslist.map(async (item, index) => {
                console.log(item, "item");
                let member = await this.app.mysql.select("userinfo", {
                    where: { id: item.member_id },
                });
                console.log(item.team_id, "vitem.team_id");
                let team = await this.app.mysql.select("volunteer_team", {
                    where: { team_id: item.team_id },
                });
                console.log(team, "team");
                let groups = await this.app.mysql.select("team_groups", {
                    where: { team_id: team[0].team_id },
                });
                team[0].groups = groups;
                memberslist[index].photo = [item.photo];
                memberslist[index].member = member[0];
                memberslist[index].team = team[0];
            }),
        );
        ctx.body = {
            code: 200,
            desp: "查询成功",
            data: memberslist,
        };
    }
    async addteammembers() {
        const { ctx, app } = this;
        let clientdata = ctx.request.body;
        const result2 = await this.app.mysql.insert("team_members", {
            team_id: clientdata.team_id,
            member_id: clientdata.member_id,
            hobbies: clientdata.hobbies,
            ismanage: "false",
            biography: clientdata.biography,
            photo: clientdata.photo[0],
            posts: "",
            state: 0,
            group_id: clientdata.group_id,
        });
        if (result2) {
            ctx.body = {
                code: 200,
                desp: "申请成功",
                data: result2,
            };
        } else {
            ctx.body = {
                code: 201,
                desp: "申请失败",
            };
        }
    }
    async updateteammembers() {
        const { ctx, app } = this;
        let clientdata = ctx.request.body;
        // 更新队伍个人信息
        const result2 = await this.app.mysql.update(
            "team_members",
            {
                posts: clientdata.posts,
                group_id: clientdata.group_id,
            },
            { where: { id: clientdata.id } },
        );
        if (result2) {
            ctx.body = {
                code: 200,
                desp: "修改成功",
                data: result2,
            };
        } else {
            ctx.body = {
                code: 201,
                desp: "修改失败",
            };
        }
    }
    async agreejointeam() {
        const { ctx, app } = this;
        let clientdata = ctx.request.body;
        console.log(clientdata);
        const result2 = await this.app.mysql.update(
            "team_members",
            {
                state: 1,
            },
            { where: { id: clientdata.id } },
        );
        if (result2) {
            ctx.body = {
                code: 200,
                desp: "审批成功",
                data: result2,
            };
        } else {
            ctx.body = {
                code: 201,
                desp: "审批失败",
            };
        }
    }
}

module.exports = TeamController;
